<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="Tc"> 
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品的级联选择框 -->
          <span>
             <el-cascader
              :options="cateList"
              :props="catProps"
              v-model="catValue"
              @change="catCasChange"
              clearable
            ></el-cascader>
          </span>
        </el-col>
      </el-row>
      <!-- 参数标签页区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数面板区域 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button 
          size="small" 
          type="primary" 
          :disabled="idBtnDisable"
          @click="showAddCatDialog"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table
            :data="manyData"
            border stripe
            style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleCloseTag(i,scope.row)"
                  >{{item}}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="addinput"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                <!-- {{scope.row}} -->
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 动态参数修改按钮 -->
                <el-button 
                type="primary"
                size="small" 
                icon="el-icon-edit"
                @click="showEditAttr(scope.row.attr_id)"
                >修改</el-button>
                <!-- 动态参数删除按钮 -->
                <el-button 
                type="danger" 
                size="small" 
                icon="el-icon-delete"
                @click="deleteAttr(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>



        <!-- 静态参数面板区域 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button 
          size="small" 
          type="primary" 
          :disabled="idBtnDisable"
          @click="showAddCatDialog"
          >添加属性</el-button>
          <!-- 静态参数表格 -->
          <el-table
            :data="onlyData"
            border stripe=""
            style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleCloseTag(i,scope.row)"
                  >{{item}}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="addinput"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                <!-- {{scope.row}} -->
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 静态属性修改按钮 -->
                <el-button 
                type="primary" 
                size="small" 
                icon="el-icon-edit"
                @click="showEditAttr(scope.row.attr_id)"
                >修改</el-button>
                <!-- 静态属性删除按钮 -->
                <el-button 
                type="danger" 
                size="small" 
                icon="el-icon-delete"
                @click="deleteAttr(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
   
    <!-- 添加参数对话框区域 -->
    <el-dialog
      :title="'添加'+catAdd"
      :visible.sync="addCatdialogVisible"
      @close="addCatdialogClosed"
      width="30%">
      <!-- 主体部分 -->
      <el-form :model="addParamData" 
               :rules="addCatRules" 
               ref="addCatRef" 
               label-width="80px ">
        <!-- 动态参数 -->
        <el-form-item :label="catAdd" prop="attr_name">
          <el-input v-model="addParamData.attr_name"></el-input>
        </el-form-item>
      </el-form> 
      <!-- 尾部 -->
      <span slot="footer" class="dialog-footer">
      <el-button @click="addCatdialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addCatDataList">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框区域 -->
    <el-dialog
      :title="'修改'+catAdd"
      :visible.sync="EditCatdialogVisible"
      @close="editCatdialogClosed"
      width="30%">
      <!-- 主体部分 -->
      <el-form :model="editParamData" 
               :rules="editCatRules" 
               ref="editCatRef" 
               label-width="80px">
        <!-- 动态参数 -->
        <el-form-item :label="catAdd" prop="attr_name">
          <el-input v-model="editParamData.attr_name"></el-input>
        </el-form-item>
      </el-form> 
      <!-- 尾部 -->
      <span slot="footer" class="dialog-footer">
      <el-button @click="EditCatdialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editCatDataList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default{
    data(){
      return{
        // 商品分类数据列表
        cateList:[],
        // 级联选择器配置
        catProps:{
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children:'children'
        },
        // 级联选择器当前选项值
        catValue:'',
        // 标签页激活项
        activeName:'many',
        // 动态参数
        manyData:[],
        // 静态属性
        onlyData:[],
        // 参数对话框显示控制
        addCatdialogVisible:false,
        // 添加的参数
        addParamData:{
          attr_name:''
        },
        // 添加参数的表单验证
        addCatRules:{
          attr_name:[
            { required: true, message: '请输入参数名', trigger: 'blur' }, 
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' } 
          ]
        },
        // 显示修改参数对话框
        EditCatdialogVisible:false,
        // 修改参数信息
        editParamData:{
        },
        // 修改参数表单规则
        editCatRules:{
          attr_name:[
            { required: true, message: '请输入参数名', trigger: 'blur' }, 
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' } 
          ]
        },
        
        
      }
    },
    created(){
      this.getCateList()
    },
    methods:{
      // 获取商品分类数据列表
      async getCateList(){
        const {data:res} = await this.$http.get('categories')
        if(res.meta.status !== 200){
          // console.log(res)
          return this.$message.error('获取商品分类数据失败！')
        }
        this.cateList = res.data
          // console.log(this.cateList)
      },
      // 级联选择器选项发生改变时
      catCasChange(){
        // console.log(this.catValue)
        
        // 获取参数列表
        this.getCatAtt()
      },
      // 标签页点击触发
      handleClick(){
        this.getCatAtt()
      },
      // 获取分类参数列表
      async getCatAtt(){
        if(this.catValue.length !== 3){
          this.manyData = []
          this.onlyData = []
          this.catValue = []
          return 0
        }
        // 发送请求
        const {data:res} = await this.$http.get(`categories/${this.catId}/attributes`, {
          params: {
            sel: this.activeName
          }
        })
        if(res.meta.status !== 200){
           return this.$message.error('获取商品参数属性失败！')
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          // 添加tag输入框是否可见
          item.inputVisible = false
          // 添加tag输入框绑定值
          item.inputValue = ''
        })
        console.log(res.data)
        // 保存参数、属性数据
        if(this.activeName === 'many'){
          this.manyData = res.data
        }else if(this.activeName === 'only'){
          this.onlyData = res.data
        }
      },
      // 显示添加参数对话框
      showAddCatDialog(){
        this.addCatdialogVisible = true
        // console.log(this.catValue)
      },
      // 添加参数对话框关闭时
      addCatdialogClosed(){
        this.$refs.addCatRef.resetFields()
      },
      // 点击按钮 添加动态参数或静态属性
      addCatDataList(){
        // console.log()
        this.$refs.addCatRef.validate(async (valid) => {
          if(!valid)  return
          const {data:res} = await this.$http.post(`categories/${this.catId}/attributes`, {
            attr_name: this.addParamData.attr_name,
            attr_sel: this.activeName
          })
          if(res.meta.status !== 201){
            return this.$message.error('添加参数失败！')
          }
          this.$message.success('添加参数成功！')
          this.getCatAtt()
          this.addCatdialogVisible = false
        })
      },
      // 修改参数对话框关闭时
      editCatdialogClosed(){
        this.$refs.editCatRef.resetFields()
      },
      // 点击修改按钮，获取参数名称
      async showEditAttr(attrId){
        // 显示修改参数对话框之前获取参数、属性名称
        const {data:res} = await this.$http.get(`categories/${this.catId}/attributes/${attrId}`, {
          attr_sel:this.activeName
        })
        if(res.meta.status !== 200){
          return this.$message.error('获取参数失败！')
        }
        this.editParamData = res.data
        
        // console.log(res)
        this.EditCatdialogVisible = true
      },
      // 点击确定按钮，提交编辑参数申请
      editCatDataList(){
        this.$refs.editCatRef.validate(async (valid) => {
          if(!valid)  return
          const {data:res} = await this.$http.put(`categories/${this.catId}/attributes/${this.editParamData.attr_id}`, {
            attr_name:this.editParamData.attr_name, attr_sel:this.activeName
          })
          // console.log(res)
          // console.log(this.activeName)
          if(res.meta.status !== 200){
            return this.$message.error('修改失败！')
          }
          this.$message.success('修改成功！')
          this.getCatAtt()
          this.EditCatdialogVisible = false
        })
      },
      // 点击删除按钮 打开确认删除弹框
      async deleteAttr(attrId){
        const result = await this.$confirm(`此操作将永久删除该${this.catAdd}, 是否继续?`, `删除${this.catAdd}`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => {
         return error
        })
        if(result === 'confirm'){
          // 发送删除参数属性请求
          const {data:res} = await this.$http.delete(`categories/${this.catId}/attributes/${attrId}`)
          if(res.meta.status !== 200){
            return this.$message.error('删除参数失败！')
          }
          this.$message.success('删除参数成功！')
          this.getCatAtt()
        }
        // console.log(result)
      },
      // 添加tag输入框确认时操作
      async handleInputConfirm(row){
        // if (inputValue) {
        //   this.dynamicTags.push(inputValue)
        // }
        if(row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return null
        }
        // 添加属性vals
        const inputValue = row.inputValue
        row.attr_vals.push(inputValue)
        row.inputValue = ''
        row.inputVisible = false
        //更新参数属性
        this.saveAttrVals(row)
      },
      // 显示文本输入框
      showInput(row){
        row.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      // Tag标签关闭时触发
      handleCloseTag(i, row){
        row.attr_vals.splice(i, 1)
        // 更新参数属性
        this.saveAttrVals(row)
      },
      // 保存更新参数属性
      async saveAttrVals(row){
        // 提交参数属性值
        const {data:res} = await this.$http.put(`categories/${this.catId}/attributes/${row.attr_id}`, {
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          attr_vals:row.attr_vals.join(',')
        })
        if(res.meta.status !== 200){
          return this.$message.error('更新失败！')
        }
        this.$message.success('更新成功！')
        // console.log(res)
      }
    },
    computed:{
      // 如果按钮需要被禁用，返回true
      idBtnDisable(){
        if(this.catValue.length !== 3){
          return true
        }
        return false
      },
      // 当前选中的三级分类ID
      catId(){
        if(this.catValue.length === 3){
          return this.catValue[2]
        }
        return null
      },
      // 对话框切换
      catAdd(){
        if(this.activeName === 'many'){
          return '动态参数'
        }else if(this.activeName === 'only'){
          return '静态属性'
        }
        return null
      }

    }
  }
</script>

<style lang="less" scoped>
.Tc{
  margin: 15px 0;
}
.el-tabs{
  margin-top: 15px;
}
.el-tag {
  margin-right: 5px;
}
.addinput {
  width: 200px;
}
</style>
